import glob

import getpass
from util_ssh import execute_commands
from util_slash import f_win, f_unix

if __name__ == "__main__":
    """主函数：获取用户输入并执行远程命令"""
    print("=== Linux远程符号链接创建工具 ===\n")

    # 获取连接参数
    # hostname = input("请输入Linux服务器IP地址: ").strip()
    # port = int(input("请输入SSH端口(默认22，直接回车使用默认值): ") or "22")
    # username = input("请输入用户名: ").strip()
    # password = getpass.getpass("请输入密码: ")

    hostname = "diskstation2"
    port = 22
    username = "admin"
    password = "mjm19831119"

    nas_driver_mapping = {
        "8192G_01": "/volume4/8192G_01",
        "8192G_02": "/volume2/8192G_02"
    }

    # 清理goodsync下所有符号链接
    rm_symbollink_command_list = [
        f"find {nas_driver_mapping['8192G_01']}/goodsync -type l -delete",
        f"find {nas_driver_mapping['8192G_02']}/goodsync -type l -delete"
    ]
    execute_commands(hostname, port, username, password, rm_symbollink_command_list)

    # 扫描goodsync中的非符号链接，要将真实文件移出goodsync目录，同时建立一个符号链接
    mv_command_list = [
        f"find {nas_driver_mapping['8192G_01']}/goodsync -maxdepth 1 ! -type l ! -name '_gsdata_' ! -name '.*' ! -name 'goodsync' -exec mv -t {nas_driver_mapping['8192G_01']}" + " {} +",
        f"find {nas_driver_mapping['8192G_02']}/goodsync -maxdepth 1 ! -type l ! -name '_gsdata_' ! -name '.*' ! -name 'goodsync' -exec mv -t {nas_driver_mapping['8192G_02']}" + " {} +"
    ]
    execute_commands(hostname, port, username, password, mv_command_list)

    # 创建符号链接（左）
    folder_list = glob.glob(r"\\diskstation2\8192G_01\*__sync")
    file_list = glob.glob(r"\\diskstation2\8192G_01\*__sync.*")
    folder_list.extend(file_list)
    ln_command_list = []
    for folder in folder_list:
        folder_name = f_unix(folder).split("/")[-1]
        folder_name = f"'{folder_name}'"
        ln_command = f"ln -s {nas_driver_mapping['8192G_01']}/{folder_name} {nas_driver_mapping['8192G_01']}/goodsync/{folder_name}"
        # ln_command_right = f"ln -s {nas_driver_mapping['8192G_02']}/{folder_name} {nas_driver_mapping['8192G_02']}/goodsync/{folder_name}"
        ln_command_list.append(ln_command)
        # ln_command_list.append(ln_command_right)
    execute_commands(hostname, port, username, password, ln_command_list)

    # 创建符号链接（右）
    folder_list = glob.glob(r"\\diskstation2\8192G_02\*__sync")
    file_list = glob.glob(r"\\diskstation2\8192G_02\*__sync.*")
    folder_list.extend(file_list)
    ln_command_list = []
    for folder in folder_list:
        folder_name = f_unix(folder).split("/")[-1]
        folder_name = f"'{folder_name}'"
        ln_command = f"ln -s {nas_driver_mapping['8192G_02']}/{folder_name} {nas_driver_mapping['8192G_02']}/goodsync/{folder_name}"
        ln_command_list.append(ln_command)
    execute_commands(hostname, port, username, password, ln_command_list)